package com.bhs.sansong.view;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

import com.bhs.sansong.utils.ToastUtil;

public class MyTextWatcher implements TextWatcher {
    private EditText editText;
    private int digits = 2;

    private int maxValue = 1000000000;

    public MyTextWatcher(EditText et) {
        editText = et;
    }

    public MyTextWatcher setDigits(int d) {
        digits = d;
        return this;
    }

    public MyTextWatcher setMaxValue(int maxValue) {
        this.maxValue = maxValue;
        return this;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //删除“.”后面超过2位后的数据
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > digits) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + digits + 1);
                editText.setText(s);
                editText.setSelection(s.length()); //光标移到最后
            }
        }
        //如果"."在起始位置,则起始位置自动补0
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            editText.setText(s);
            editText.setSelection(2);
        }

        //如果起始位置为0,且第二位跟的不是".",则无法后续输入
        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (s.toString().charAt(1) != '.') {
                editText.setText(s.subSequence(0, 1));
                editText.setSelection(1);
                return;
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(s) && !s.toString().equals(".")) {
            if (Float.parseFloat(s.toString()) > maxValue) {
                editText.setText("");
                ToastUtil.show(String.format("最大值不可以超过%s", maxValue));
            }
            if (afterTextChanged != null) {
                afterTextChanged.onCallBack(editText.getText().toString());
            }
        }
    }

    private AfterTextChanged afterTextChanged;

    public void addTextChangedListener(AfterTextChanged afterTextChanged) {
        this.afterTextChanged = afterTextChanged;
    }
}

